package com.star.utils;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringUtils;

import java.io.IOException;

/**
 * @Author chaoyang
 * @Description:
 * @Date 2019/9/7 0007
 * @Version V1.0
 **/
public class JackonUtils {

    public final static ObjectMapper objectMapper = new ObjectMapper();


    public static <T> String toJson(T t) {
        if(t == null) return null;
        String result = null;
        try {
            result = objectMapper.writeValueAsString(t);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static <T> T formJson(String json, Class<T> clazz) {

        if (StringUtils.isNotBlank(json)) {
            try {
                return objectMapper.readValue(json, clazz);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    /**
     * @param parametrized
     * @param parameterClasses
     * @return
     */
    private static JavaType constructParametricType(Class<?> parametrized, Class<?>... parameterClasses) {
        return objectMapper.getTypeFactory().constructParametricType(parametrized, parameterClasses);
    }

    /**
     * @param jsonString
     * @param parametrized     List.class
     * @param parameterClasses Man.class
     * @return
     */
    public static <T> T fromJson(String jsonString, Class<?> parametrized, Class<?>... parameterClasses) {
        if (StringUtils.isNotBlank(jsonString)) {
            JavaType javaType = constructParametricType(parametrized, parameterClasses);
            try {
                return objectMapper.readValue(jsonString, javaType);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
